package com.zl.tby.service.impl;

import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyLayerConfigQuery;
import com.zl.tby.model.TbyLayerConfig;
import com.zl.tby.model.TbyUavInfo;
import com.zl.tby.repository.TbyLayerConfigRepo;
import com.zl.tby.service.ITbyLayerConfigService;
import com.zl.tby.vo.TbyLayerConfigForm;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.IPage;
import org.noear.wood.annotation.Db;
import org.noear.wood.impl.IPageImpl;
import org.noear.wood.utils.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 地图图层配置
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Component
public class TbyLayerConfigServiceImpl implements ITbyLayerConfigService {

    @Db
    private TbyLayerConfigRepo tbyLayerConfigRepo;

    @Override
    @Tran
    public R<TbyLayerConfig> add(TbyLayerConfigForm form) {
        TbyLayerConfig entity = form.createEntity();
        entity.setCreateBy(ToolsUtil.getLoginUserId());
        entity.setCreateTime(LocalDateTime.now());
        if (entity.getActive() == null) {
            entity.setActive(0);
        }
        // 当前新增开启，其他的要变为不启用
        if (entity.getActive().compareTo(1) == 0) {
            clearAllActive();
        }
        long id = tbyLayerConfigRepo.insert(entity, true);
        entity.setId(id);
        return R.ok(entity);
    }

    @Override
    @Tran
    public R<TbyLayerConfig> update(TbyLayerConfigForm form) {
        TbyLayerConfig entity = this.get(form.getId());
        if (entity == null) {
            return R.failed("数据不存在");
        }
        // 原来未启用， 修改后启用，清除原来启用的
        if (entity.getActive().compareTo(0) == 0 && form.getActive().compareTo(1) == 0) {
            clearAllActive();
        }
        form.updateEntity(entity);
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        if (entity.getActive() == null) {
            entity.setActive(0);
        }
        tbyLayerConfigRepo.updateById(entity, false);
        return R.ok(entity);
    }

    @Override
    public R<Void> delete(Long id) {
        int flag = tbyLayerConfigRepo.deleteById(id);
        return flag > 0 ? R.ok() : R.failed("删除失败");
    }

    @Override
    public TbyLayerConfig get(Long id) {
        return tbyLayerConfigRepo.selectById(id);
    }

    @Override
    public TbyPageResult<TbyLayerConfigForm> page(TbyLayerConfigQuery query) {
        IPage<TbyLayerConfig> iPage = tbyLayerConfigRepo.selectPage(query.getOffset(), query.getSize(), mp -> {
            mp.whereTrue()
                    .andIf(ToolsUtil.isNotNull(query.getActive()), "active = ?", query.getActive())
                    .andIf(StringUtils.isNotEmpty(query.getName()), "name like ?", "%" + query.getName() + "%");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        List<TbyLayerConfigForm> formList = new ArrayList<>();
        iPage.getList().forEach(item -> {
            formList.add(TbyLayerConfigForm.convert(item));
        });
        return new TbyPageResult(new IPageImpl(formList, iPage.getTotal(), iPage.getSize()), query);
    }

    @Override
    public List<TbyLayerConfig> list(TbyLayerConfigQuery query) {
        return tbyLayerConfigRepo.selectList(mp -> {
            mp.whereTrue()
                    .andIf(ToolsUtil.isNotNull(query.getActive()), "active = ?", query.getActive())
                    .andIf(StringUtils.isNotEmpty(query.getName()), "name like ?", "%" + query.getName() + "%");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
    }

    @Override
    @Tran
    public R<Void> active(Long id, Integer active) {
        if (active.compareTo(1) == 0) {
            // 如果设置成了1，需要先将原来的1设置成0
            clearAllActive();
        }
        TbyLayerConfig entity = new TbyLayerConfig();
        entity.setId(id);
        entity.setActive(active);
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        tbyLayerConfigRepo.updateById(entity, true);
        return R.ok();
    }

    /**清除当前选择*/
    private void clearAllActive() {
        TbyLayerConfigQuery query = new TbyLayerConfigQuery();
        query.setActive(1);
        List<TbyLayerConfig> activeList = this.list(query);
        for (TbyLayerConfig config : activeList) {
            config.setActive(0);
            config.setUpdateBy(ToolsUtil.getLoginUserId());
            config.setUpdateTime(LocalDateTime.now());
            tbyLayerConfigRepo.updateById(config, false);
        }
    }

    @Override
    public R<Boolean> checkName(Long id, String name) {
        if (StringUtils.isEmpty(name)) {
            return R.ok(false);
        }
        List<TbyLayerConfig> dbList = this.tbyLayerConfigRepo.selectList(mp -> {
            mp.whereEq("name", name);
        });
        for (TbyLayerConfig data : dbList) {
            if (id == null && data.getName().equals(name)) {
                return R.ok(true);
            } else if (id != null && data.getName().equals(name) && id.compareTo(data.getId()) != 0) {
                return R.ok(true);
            }
        }
        return R.ok(false);
    }

    @Override
    public R<Boolean> checkUrl(Long id, String url) {
        if (StringUtils.isEmpty(url)) {
            return R.ok(false);
        }
        List<TbyLayerConfig> dbList = this.tbyLayerConfigRepo.selectList(mp -> {
            mp.whereEq("url", url);
        });
        for (TbyLayerConfig data : dbList) {
            if (id == null && data.getUrl().equals(url)) {
                return R.ok(true);
            } else if (id != null && data.getUrl().equals(url) && id.compareTo(data.getId()) != 0) {
                return R.ok(true);
            }
        }
        return R.ok(false);
    }
}
